package com.minggo.charmword.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;

import com.baidu.mobstat.StatService;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.minggo.charmword.R;
import com.minggo.charmword.adapter.WordPagerAdpater;
import com.minggo.charmword.fragment.FragmentFind;
import com.minggo.charmword.fragment.FragmentMine;
import com.minggo.charmword.fragment.FragmentReview;
import com.minggo.charmword.fragment.FragmentUserCenter;
import com.minggo.charmword.service.CharmWordApplication;
import com.minggo.charmword.service.CharmWordService;
import com.minggo.charmword.util.PhotoUtil;
import com.minggo.charmword.util.SharePreferenceUtil;
import com.minggo.charmword.view.WordDialog;
import com.minggo.charmword.view.WordDialog.OnDialogClickListener;

/**
 * 首页
 * 
 * @author minggo
 * @time 2014-8-28 S下午9:43:06
 */
public class IndexActivity extends SlidingFragmentActivity implements OnClickListener,OnDialogClickListener{

	private static final int IMAGECROP = 1005;
	protected FragmentUserCenter usercenterFgm;
	private View openBt;

	private List<Fragment> fragmentList = new ArrayList<Fragment>();
	private ImageView naviBottomIv;
	private int currIndex = 1;// 当前页卡编号
	private int defaultIndex = 1;// 默认的第一页面

	public ViewPager viewPager;
	private WordPagerAdpater pagerAdpater;

	private Button feelingBt;
	private Button seziBt;
	private Button alertBt;
	private FragmentMine mineFgm;
	private FragmentReview reviewFgm;
	private FragmentFind findFgm;
	private ImageView searchBt;
	private SlidingMenu sm;

	private boolean isFirst;// 判断是不是第一次打开运用
	private SharedPreferences preferences;
	private int item_width;
	private int endPosition;
	private int beginPosition;
	private boolean isEnd;
	
	private WordDialog exitdDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_index);
		
		exitdDialog = new WordDialog(this, R.style.select_dialog, WordDialog.TWO_BUTTON, getString(R.string.dailog_title), getString(R.string.app_exit_content), this);
		
		setTitle("no title");
		
		this.startService(new Intent(this, CharmWordService.class));
		preferences = getSharedPreferences("first", Context.MODE_PRIVATE);
		isFirst = preferences.getBoolean("isfrist", true);
		makeShortCut(isFirst);
		initView();
		CharmWordApplication.allActivities.add(this);
		setBehindContentView(R.layout.menu_frame);
		if (savedInstanceState == null) {
			FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
			usercenterFgm = new FragmentUserCenter();
			t.replace(R.id.menu_frame, usercenterFgm);
			t.commit();
		} else {
			usercenterFgm = (FragmentUserCenter) this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
		}
		
	}

	/**
	 * 初始化UI
	 */
	private void initView() {
		
		initImageView();
		
		// customize the SlidingMenu
		sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);

		openBt = findViewById(R.id.lo_index_menu);
		viewPager = (ViewPager) findViewById(R.id.index_viewPager);
		alertBt = (Button) findViewById(R.id.bt_index_alert);
		seziBt = (Button) findViewById(R.id.bt_index_seii);
		feelingBt = (Button) findViewById(R.id.bt_index_feeling);
		searchBt = (ImageView) findViewById(R.id.bt_index_search);
		alertBt.setOnClickListener(this);
		seziBt.setOnClickListener(this);
		feelingBt.setOnClickListener(this);
		searchBt.setOnClickListener(this);
		openBt.setOnClickListener(this);

		findFgm = new FragmentFind();
		reviewFgm = new FragmentReview();
		mineFgm = new FragmentMine();

		fragmentList.add(mineFgm);
		fragmentList.add(reviewFgm);
		fragmentList.add(findFgm);
		
		
		
		pagerAdpater = new WordPagerAdpater(getSupportFragmentManager(), fragmentList);
		viewPager.setAdapter(pagerAdpater);
		viewPager.setOffscreenPageLimit(3);
		viewPager.setCurrentItem(currIndex);
		viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int position) {
			
			if (position == ViewPager.SCROLL_STATE_DRAGGING) {
				isEnd = false;
			} else if (position == ViewPager.SCROLL_STATE_SETTLING) {
				isEnd = true;
				beginPosition = currIndex * item_width;
				if (viewPager.getCurrentItem() == currIndex) {
					// 未跳入下一个页面
					naviBottomIv.clearAnimation();
					Animation animation = null;
					// 恢复位置
					animation = new TranslateAnimation(endPosition, currIndex * item_width, 0, 0);
					animation.setFillAfter(true);
					animation.setDuration(100);
					naviBottomIv.startAnimation(animation);
					endPosition = currIndex * item_width;
				}
			}
		}
		
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			if (!isEnd) {
				if (currIndex == position) {
					endPosition = item_width * currIndex + (int) (item_width * positionOffset);
				}
				if (currIndex == position + 1) {
					endPosition = item_width * currIndex - (int) (item_width * (1 - positionOffset));
				}

				Animation mAnimation = new TranslateAnimation(beginPosition, endPosition, 0, 0);
				mAnimation.setFillAfter(true);
				mAnimation.setDuration(100);
				naviBottomIv.startAnimation(mAnimation);
				beginPosition = endPosition;
			}
		}

		public void onPageSelected(int position) {

			Animation animation = new TranslateAnimation(endPosition, position * item_width, 0, 0);

			beginPosition = position * item_width;

			currIndex = position;
			if (animation != null) {
				animation.setFillAfter(true);
				animation.setDuration(100);
				naviBottomIv.startAnimation(animation);
			}

			tabSelected(position);
			
			StatService.onPageEnd(IndexActivity.this, getFragment(currIndex));
			StatService.onPageStart(IndexActivity.this, getFragment(position));
			//translate(position);

			switch (position) {
			case 0:
				getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
				break;
			default:
				getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
				break;
			}
		}
	}

	/** 导航底层图片移动当当前选择页面
	 * 
	 * @param tab
	 */
	private void tabSelected(final int tab) {
		alertBt.setSelected(tab == 0 ? true : false);
		seziBt.setSelected(tab == 1 ? true : false);
		feelingBt.setSelected(tab == 2 ? true : false);
		
	}
	
	@Override
	public void onBackPressed() {
		exitdDialog.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		StatService.onPageStart(IndexActivity.this, getFragment(currIndex));
	}

	/**
	 * 获取fragment名字
	 * 
	 * @param index
	 * @return
	 */
	private String getFragment(int index) {

		String labelId = "";
		switch (index) {
		case 0:
			labelId = "page_history";
			break;
		case 1:
			labelId = "page_review";
			break;
		case 2:
			labelId = "page_word_store";
			break;

		default:
			break;
		}
		return labelId;

	}

	
	/**
	 * 初始化导航条
	 */
	private void initImageView() {
		
		
		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		naviBottomIv = (ImageView) this.findViewById(R.id.cursor);
		
		Matrix matrix = new Matrix();
		matrix.postTranslate(defaultIndex * (screenW / 3), 0);
		naviBottomIv.setImageMatrix(matrix);// 设置动画初始位置
		
		item_width = (int) ((screenW / 3));
		
		naviBottomIv.getLayoutParams().width = item_width;
		
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.bt_index_search:
			startActivity(new Intent(this, SearchActivity.class));
			break;
		case R.id.lo_index_menu:
			toggle();
			break;
		case R.id.bt_index_alert:
			viewPager.setCurrentItem(0);
			break;
		case R.id.bt_index_seii:
			viewPager.setCurrentItem(1);
			break;
		case R.id.bt_index_feeling:
			viewPager.setCurrentItem(2);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		StatService.onPageEnd(IndexActivity.this, getFragment(currIndex));
	}

	/**
	 * 设置快捷键
	 * 
	 * @param isFirst
	 */
	private void makeShortCut(boolean isFirst) {

		if (isFirst) {
			Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
			shortcutIntent.putExtra("duplicate", false);
			shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
			Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.logo);
			shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
			Intent intent = new Intent(getApplicationContext(), IndexActivity.class);
			intent.setAction("android.intent.action.MAIN");
			intent.addCategory("android.intent.category.LAUNCHER");
			shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
			sendBroadcast(shortcutIntent);
			// 设置不是第一次进入标尺
			SharedPreferences.Editor editor = preferences.edit();
			editor.putBoolean("isfrist", false);
			editor.commit();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == FragmentUserCenter.REQUEST_LOGIN) {
			if (resultCode == LoginActivity.LOGIN_SUCCESS) {
				usercenterFgm.requestData();
			}
		}
		
		switch (requestCode) {
		case FragmentUserCenter.REQUEST_LOGIN:
			
			break;
		case FragmentUserCenter.GET_USER_CAMERA:
			String imagePath = SharePreferenceUtil.getUserAvatar(this);
			if (resultCode == RESULT_OK) {

				if (imagePath != null) {
					Display display = getWindowManager().getDefaultDisplay();
					PhotoUtil.compressImage(imagePath, 100, display);

					Intent intent = new Intent(IndexActivity.this, ImageClipActivity.class);
					intent.putExtra("imagePath", imagePath);
					startActivityForResult(intent, IMAGECROP);
				}
			}
			break;
		case FragmentUserCenter.GET_USER_GALLERY:
			
			String imagePath1 = SharePreferenceUtil.getUserAvatar(this);
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri uri = data.getData();
					Display display = getWindowManager().getDefaultDisplay();
					Bitmap bitmap = PhotoUtil.getBitpMap(IndexActivity.this, uri, display);
					if (bitmap != null) {

						Matrix matrix = new Matrix();
						matrix.setRotate(PhotoUtil.readPictureDegree(PhotoUtil.getPath(IndexActivity.this, uri)));
						Bitmap saveBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
						PhotoUtil.writeToFile(imagePath1, saveBitmap, 100);
						bitmap.recycle();
						Intent intent = new Intent(IndexActivity.this, ImageClipActivity.class);
						intent.putExtra("imagePath", imagePath1);
						startActivityForResult(intent, IMAGECROP);
					}
				}
			}
			break;
		case IMAGECROP:
			if (resultCode == ImageClipActivity.RETURN_IMAGE) {
				usercenterFgm.setAvatar();
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onDialogClick(int state) {
		switch (state) {
		case WordDialog.BUTTON_LEFT:
			exitdDialog.dismiss();
			break;
		case WordDialog.BUTTON_RIGHT:
			exitdDialog.dismiss();
			exitdDialog = null;
			StatService.onPageEnd(IndexActivity.this, getFragment(currIndex));
			super.onBackPressed();
			CharmWordApplication.getInstance().stopAPP();
			break;
		default:
			break;
		}
	}
	
}
